package com.imay.live.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.manager.ActivityStackManager;
import com.imay.base.util.NetworkUtil;
import com.imay.cocos.IMayCocos;
import com.imay.live.Constants;
import com.imay.live.R;
import com.imay.live.adapter.ChangeRoomShortAdapter1;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.fragment.room.LiveRecordFragment;
import com.imay.live.helper.CallBack;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.model.RoomInfoModel;
import com.imay.live.model.ShortLiveInfoModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.room.ShortLivePlayResp;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.utils.TimeUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.custom.RoomBaseView;
import com.imay.live.view.custom.RoomLiveShortView;
import com.imay.live.view.dialog.ShareDialogFragment;
import com.imay.tsnackbar.TSnackbar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.imay.live.activity.ProfileActivity.FROM_TYPE_SHORT_LIVE;


/**
 * Created by jeaman on 2017/3/28.
 */

public class RoomLiveShortActivity extends RoomLiveBaseActivity implements RoomLiveShortView.OnLiveActionListener {
    private static String SHORT_LIVE_ID = "SHORT_LIVE_ID";
    private static String TARGET_USER_ID = "TARGET_USER_ID";
    private static String TOPIC_ID = "TOPIC_ID";
    private static String FAMILY_ID = "FAMILY_ID";
    private static String SORT_TYPE = "SORT_TYPE";
    private static String SHOW_GIRL_LIVE_BOTTON = "SHOW_GIRL_LIVE_BOTTON";
    private static String SHORT_LIVE_ID_LIST= "SHORT_LIVE_ID_LIST";
    private static String SINGLE= "SINGLE";

    private static long COUNT_DOWN_TIME = 30000;    //30秒倒计时

    private ShortLiveInfoModel mShortLiveInfo;
    private ChangeRoomShortAdapter1 mAdapter;
    //    private Map<Long, ShortLiveInfoModel> mShortLiveMap = new LinkedHashMap<>();
    private List<Long> mShortLiveIdList = new ArrayList<>();
    private long mTargetUid;
    private boolean noMoreProfileShortLive;
    private String mRequestId;
    private long mTargetShortId;
    private int mLastViewPosition = -1;
    private boolean mShowChallengeTips;
    private long topicId,familyId;
    private int sortType;
    private long followUid;//当前关注的主播ID 用于当前点击关注时候 记录数据
    private boolean mLiveMode;  //当前是否直播模式
    private long mShortLiveId;
    private boolean isSingle; // 是否只播放单个超胆播, 不能滑动

    public static void startActivity(Context context) {
        ActivityStackManager.getInstance().clearActivitys(RoomLiveNormalActivity.class);
        Intent intent = new Intent(context, RoomLiveShortActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, boolean showGirlLiveBotton) {
        ActivityStackManager.getInstance().clearActivitys(RoomLiveNormalActivity.class);
        Intent intent = new Intent(context, RoomLiveShortActivity.class);
        intent.putExtra(SHOW_GIRL_LIVE_BOTTON, showGirlLiveBotton);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, List<Long> mShortLiveIdList, long uid) {
        ActivityStackManager.getInstance().clearActivitys(RoomLiveNormalActivity.class);
        Intent intent = new Intent(context, RoomLiveShortActivity.class);
        intent.putExtra(TARGET_USER_ID, uid);
        intent.putExtra(SHORT_LIVE_ID_LIST, (Serializable) mShortLiveIdList);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, List<Long> mShortLiveIdList,long topicId ,int type) {
        ActivityStackManager.getInstance().clearActivitys(RoomLiveNormalActivity.class);
        Intent intent = new Intent(context, RoomLiveShortActivity.class);
        intent.putExtra(TOPIC_ID, topicId);
        intent.putExtra(SORT_TYPE, type);
        intent.putExtra(SHORT_LIVE_ID_LIST, (Serializable) mShortLiveIdList);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }
    //家族超胆播
    public static void startActivityforFamily(Context context, List<Long> mShortLiveIdList,long familyId ) {
        ActivityStackManager.getInstance().clearActivitys(RoomLiveNormalActivity.class);
        Intent intent = new Intent(context, RoomLiveShortActivity.class);
        intent.putExtra(FAMILY_ID, familyId);
        intent.putExtra(SHORT_LIVE_ID_LIST, (Serializable) mShortLiveIdList);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }


    public static void startLiveActivity(Context context, long shortLiveId,boolean single) {
        ActivityStackManager.getInstance().clearActivitys(RoomLiveNormalActivity.class);
        Intent intent = new Intent(context, RoomLiveShortActivity.class);
        intent.putExtra(SHORT_LIVE_ID, shortLiveId);
        intent.putExtra(SINGLE, single);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initData(intent);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        mCoverIv.setImageResource(R.mipmap.pic_03chaodanbo_bg);
        initData(getIntent());
    }

    private void initData(Intent intent) {
        mTargetUid = intent.getLongExtra(TARGET_USER_ID, 0);
        topicId = intent.getLongExtra(TOPIC_ID, 0);
        familyId = intent.getLongExtra(FAMILY_ID, 0);
        sortType = intent.getIntExtra(SORT_TYPE, 0);
        isSingle = intent.getBooleanExtra(SINGLE, false);
        List<Long> shortLiveIds = (List<Long>) intent.getSerializableExtra(SHORT_LIVE_ID_LIST);
        long shortLiveId;
        if (shortLiveIds!=null&&!shortLiveIds.isEmpty()){
            mShortLiveIdList.addAll(shortLiveIds);
        }else{
            shortLiveId = intent.getLongExtra(SHORT_LIVE_ID, 0);
            if (shortLiveId != 0) {
                mShortLiveIdList.add(shortLiveId);
            }
        }

        boolean plusOne = !isHasNextShortId(); //超胆集不需要加1
        mAdapter = new ChangeRoomShortAdapter1(this, plusOne);
        mViewPager.setAdapter(mAdapter);

        mShowChallengeTips = PreferenceHelper.getInstance().getChallenge();
        if (mShortLiveIdList.size()>1){
//            changeRoom(mShortLiveIdList.size()-1);
            mAdapter.setCount(mShortLiveIdList.size());
            mViewPager.setCurrentItem(mShortLiveIdList.size()-1);
        }else{
            changeRoom(0);
        }
        getRoomView().setGirlLiveViewVisibility(intent.getBooleanExtra(SHOW_GIRL_LIVE_BOTTON,false));
        MobclickAgent.onEvent(this, "cdb_watch_watch");
    }

    private void viewNext(long targetShortLiveId) {
        mTargetShortId = targetShortLiveId;
        if (topicId!=0){
            mRequestId = ProtoRequestHelper.task(ProtoHttpFactory.requestViewNextShortLiveTopic(getShortLiveId(), targetShortLiveId, topicId,sortType)).setTag(this.hashCode()).request(this);
        }else if(familyId!=0){
            mRequestId = ProtoRequestHelper.task(ProtoHttpFactory.requestViewNextShortLiveFamily(getShortLiveId(), targetShortLiveId, familyId)).setTag(this.hashCode()).request(this);
        }else{
            mRequestId = ProtoRequestHelper.task(ProtoHttpFactory.requestViewNextShortLive(getShortLiveId(), targetShortLiveId,mTargetUid)).setTag(this.hashCode()).request(this);
        }

    }

    @Override
    public void onRequestSuccess(String command, String data) {
        if (isDestroyed()) {
            return;
        }
        if (command.equals(mRequestId)) {
            Result<ShortLivePlayResp> result = JSON.parseObject(data, new TypeReference<Result<ShortLivePlayResp>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess && result.data != null) {
                mShortLiveId = result.data.getShortLiveInfo().getShortLiveId();
                IMayCocos.enterRoomByShortLive(mShortLiveId, JSON.toJSONString(result.data));
                UserInfoCard user = result.data.getHostessInfo();
                onJoinRoom(user);
                startPlayShortLive(result.data.getShortLiveInfo(), result.data.getNextShortLiveId());
                if (user.myFollow) {
                    followUid = user.uid;
                }
                if (user.uid != AccountManager.getInstance().getUid()) {    //自己不显示直播状态
                    getRoomView().setLiveStatus(user, this);
                }
            }
        }
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        if (isDestroyed()) {
            return;
        }
        if (command.equals(mRequestId)) {
            if (code == ResultCode.CodeShortLiveNoMore) {
                //没有更多短直播可以观看
                ToastUtil.show(RoomLiveShortActivity.this, R.string.short_live_no_more);
                onBackPressed();
            } else {
                ErrorResult.toastError(RoomLiveShortActivity.this, code);
            }
        }
    }

    private long getShortLiveId() {
        return mShortLiveInfo == null ? 0 : mShortLiveInfo.getShortLiveId();
    }

    private long getShortLiveId(int position) {
        if (position >= 0 && position < mShortLiveIdList.size()) {
            return mShortLiveIdList.get(position);
        } else {
            return 0;
        }
    }

    private void startPlayShortLive(ShortLiveInfoModel shortLiveInfo, long nextShortLiveId) {
        mShortLiveInfo = shortLiveInfo;
        if (mTargetShortId == 0) {   //请求新数据才添加
            Long shortLiveId = shortLiveInfo.getShortLiveId();
            mShortLiveIdList.add(shortLiveId);
        }
        if (isHasNextShortId()) {
            if (nextShortLiveId > 0) {  //如果有下一条id，则添加到列表,如果有下一条id的时候，最后一页不需要请求最新的，所以adapter的setCount需要减1
                if (!mShortLiveIdList.contains(nextShortLiveId)) {
                    mShortLiveIdList.add(nextShortLiveId);
                }
                noMoreProfileShortLive = false;
            } else {
                noMoreProfileShortLive = true;
            }
        }
        mAdapter.setCount(mShortLiveIdList.size());

        //直播才显示礼物按钮
        if (shortLiveInfo.getStatus() == 1) {
            getRoomView().setGiftViewVisibility(true);
        }
        getRoomView().showAllView();
        getRoomView().setChallengeTitle(shortLiveInfo.getChallengeTitle());
        getRoomView().setChallengeContent(shortLiveInfo.getChallengeContent());
        if (!mShowChallengeTips) {
            mShowChallengeTips = true;
            PreferenceHelper.getInstance().setChallenge();
            getRoomView().showChallengeNotify();
        }

        if (!TextUtils.isEmpty(shortLiveInfo.getPullStreamUrl())) {
            mLiveMode = true;
            mLivePlayer.setLiveUrl(shortLiveInfo.getPullStreamUrl());
            startPlay();
        } else if (!TextUtils.isEmpty(shortLiveInfo.getVideoUrl())) {
            mLiveMode = false;
            mLivePlayer.setVodUrl(shortLiveInfo.getVideoUrl());
            startPlay();
        }
    }

    private RoomLiveShortView getRoomView() {
        return (RoomLiveShortView) mRoomView;
    }

    private void startLiveByRoomId(long roomId) {
        ProtoRequestHelper.task(ProtoHttpFactory.getRoomInfo(roomId)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                try {
                    Result<RoomInfoModel> result = JSON.parseObject(data, new TypeReference<Result<RoomInfoModel>>() {
                    }.getType());
                    if (result.result == ResultCode.CodeSuccess && result.data != null) {
                        RoomLiveNormalActivity.startActivity(RoomLiveShortActivity.this, result.data);
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                ErrorResult.toastError(RoomLiveShortActivity.this, code);
            }
        });
    }

    @Override
    protected RoomBaseView createRoomView() {
        RoomLiveShortView roomLiveShortView = new RoomLiveShortView(this);
        roomLiveShortView.setOnLiveActionListener(this);
        return roomLiveShortView;
    }

    @Override
    protected void shareRoom() {
        if (mShortLiveInfo != null) {
            MobclickAgent.onEvent(this, "cdb_watch_share");
            String image = mShortLiveInfo.getStatus() == 9 ? UrlHelper.getVideoThumbUrl(mShortLiveInfo.getVideoUrl()) : mAnchorInfo.imgHead;
            String url = UrlHelper.getShareShortLiveUrl(mShortLiveInfo.getShortLiveId());
            String title = getString(mShortLiveInfo.getStatus() == 1 ? R.string.short_live_share_title : R.string.short_live_video_share_title, mAnchorInfo.nick);
            String des = mShortLiveInfo.getChallengeContent();
            DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), ShareDialogFragment.newInstance(ShareDialogFragment.WEB, url, title, des, image));
        }
    }

//    @Override
//    public void onStop() {
//        super.onStop();
//        getRoomView().startCountDown();
//    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ActivityStackManager.getInstance().clearAll();
        MobclickAgent.onEvent(this, "cdb_challenge_close");
    }

    @Override
    protected void cocosExitRoomByType() {
        IMayCocos.exitRoomByShortLive(mShortLiveId);
    }

    @Override
    protected void requestLeaveRoom() {
        long shortLiveId = getShortLiveId();
        if (shortLiveId != 0) {
            ProtoRequestHelper.task(ProtoHttpFactory.requestViewEndShortLive(shortLiveId)).setTag(this.hashCode()).request(null);
        }
    }

    @Override
    protected void onChangeRoom(int position) {
        if (mShortLiveId != 0) {
            cocosExitRoomByType();   //cocos先退出房间
        }
        getRoomView().hideAllView();
        viewNext(getShortLiveId(position));
        if (!isHasNextShortId() && mLastViewPosition > position) {   //往上翻，移除后面的
            for (int i = mShortLiveIdList.size() - 1; i > position; i--) {
                mShortLiveIdList.remove(i);
            }
            mAdapter.setCount(mShortLiveIdList.size());
        }
        mLastViewPosition = position;
    }

    private void changeToNextRoom() {
        mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
    }

    private void holdCallLive(UserInfoCard userInfoCard) {
        HoldCallLiveActivity.startActivity(this, userInfoCard.uid, userInfoCard.nick);
    }

    @Override
    protected void onLiveEnd() {
        //不停止播放，等返回播放错误
    }

    @Override
    protected void updateFollowAnchorView(long uid, boolean isFollow) {
        super.updateFollowAnchorView(uid, isFollow);
        if (isFollow) {
            followUid = uid;
        } else if (followUid == uid) {
            followUid = 0;
        }
    }

    @Override
    protected void setCoverViewVisibility(int position, boolean visible) {
        mAdapter.setViewVisibility(position, visible);
    }

    @Override
    public void onPlayBegin() {
        super.onPlayBegin();
        if (mLiveMode) {
            getRoomView().startCountDown(COUNT_DOWN_TIME);
        } else {
            getRoomView().setCountDownTime(COUNT_DOWN_TIME);
        }
        if (!AccountManager.getInstance().isMyself(mAnchorInfo.uid)) {
            IMayCocos.showShortLiveLike();
        }
    }

    @Override
    public void onPlayEnd() {
        if (isHasNextShortId() && noMoreProfileShortLive) {
            ToastUtil.show(this, R.string.nomore_short_live);
        } else {
            changeToNextRoom();
        }
    }

    @Override
    public void onPlayReconnect(int count) {
        if (mLiveMode && (count % 3 == 0)) {
            //如果当前有网络，重连时，如果是直播流，切换超胆播
            if (NetworkUtil.hasNetwork(this)) {
                changeToNextRoom();
            }
        }
    }

    @Override
    public void onPlayProgress(int progress, int duration) {
        getRoomView().setCountDownTime(COUNT_DOWN_TIME - (progress * 1000));
    }

    @Override
    public void onGiftClick() {
        IMayCocos.showGiftPanel();
    }

    @Override
    public void onScreenShotClick() {
        screenShot(SCREENSHOT_SHARE);
    }

    @Override
    public void onShareClick() {
        shareRoom();
    }

    @Override
    public void onRecordClick() {
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), LiveRecordFragment.newInstance());
    }

    @Override
    public void onChallengeClick() {
        RoomPushShortActivity.startActivity(this);
        onBackPressed();
    }

    @Override
    public void onGirlLiveClick() {
        onBackPressed();
    }

    @Override
    public void onCallLiveClick(final UserInfoCard userInfoCard) {
        if (userInfoCard.LiveStatus == 1) {
            startLiveByRoomId(userInfoCard.roomId);
        } else {
            if (userInfoCard.uid == followUid) {
                holdCallLive(userInfoCard);
            } else {
                //弹出关注对话框，关注后直接跳转
                DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), null, getString(R.string.str_calltips), getString(R.string.button_follow), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        followUser(userInfoCard.uid, new CallBack() {
                            @Override
                            public void onSuccess() {
                                if (!isDestroyed()) {
                                    holdCallLive(userInfoCard);
                                }
                            }

                            @Override
                            public void onError(int code, String message) {

                            }
                        });
                    }
                });
//                ToastUtil.show(this, getResources().getString(R.string.str_calltips));
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    //查看指定用户或指定专题的超胆播的时候会有值
    private boolean isHasNextShortId() {
        return topicId!=0||familyId!=0||mTargetUid!=0||isSingle;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.DYNAMICSFEED_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                TSnackbar.make(getDecorView(), getString(R.string.str_realse_send_sucess)).show();
            }
        }
    }

    @Override
    public void onUserHeadClick(UserInfoCard userInfoCard) {
        ProfileActivity.start(this,userInfoCard.uid,FROM_TYPE_SHORT_LIVE);
    }
}

